package util.qRcode;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
import java.util.Random;

/**
 * 二维码 工具类
 * @Author zt
 * @date 2021/11/12 17:31
 * @Version 1.0
 */
public class QRCodeUtil {
    /**
     * 输出二维码方式：本地文件的方式
     *
     * @param content  二维码图片展示的内容
     * @param logPath  log图片的路径
     * @param width    二维码的宽
     * @param height   二维码的高
     * @param filePath 保存二维码的地址
     */
    public static void localFile(String content, String logPath, int width, int height, String filePath) throws Exception {
        BufferedImage bufImg = makeMatrixImg(content, logPath, width, height);
        OutputStream os = new FileOutputStream(filePath);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
        encoder.encode(bufImg);
    }

    /**
     * 输出二维码的方式：stream流的方式
     *
     * @param content 二维码图片展示的内容
     * @param logPath log图片的路径
     * @param width   二维码的宽
     * @param height  二维码的高
     * @return  结果
     */
    public static String steamPrintln(String content, String logPath, int width, int height) throws Exception {
        BufferedImage bufferedImage = makeMatrixImg(content, logPath, width, height);
        try {
            // ByteArrayOutputStream或ByteArrayInputStream是内存读写流，
            // 不同于指向硬盘的流，它内部是使用字节数组读内存的，这个字节数组是它的成员变量，
            // 当这个数组不再使用变成垃圾的时候，Java的垃圾回收机制会将它回收。所以不需要关流!
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", out);
            // 将流转成数组
            byte[] bytes = out.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            return "data:image/png;base64," + encoder.encodeBuffer(bytes).trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 生成二维码的方法
     * 存在log图片时候输入含有log图片的二维码，log图片不存在时候输出不含log图片的二维码
     *
     * @param content 二维码图片展示的内容
     * @param logPath log图片的路径
     * @param width   二维码的宽
     * @param height  二维码的高
     * @throws Exception 异常
     */
    public static BufferedImage makeMatrixImg(String content, String logPath, int width, int height) throws Exception {
        // 将内容写入矩阵
        Hashtable<EncodeHintType, String> matrix = new Hashtable<EncodeHintType, String>();
        // 设置矩阵所使用的编码格式
        matrix.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 初始化矩阵，并将矩阵图形化
        BufferedImage matrixImage = toBufferredImage(new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, matrix));
        // 读取log图片
        File file = new File(logPath);
        if (file.exists()) {
            BufferedImage logImage = ImageIO.read(file);
            // log图片过大，使得二维码无法扫描
            // 判断log图片是否过大，log图片的大小不大于二维码大小的六分之一
            int oneSixthW = width / 6;
            int oneSixthH = height / 6;
            if (logImage.getWidth() > oneSixthW || logImage.getHeight() > oneSixthH) {
                // 重新生成一个合适的log图片
                BufferedImage newImage = new BufferedImage(oneSixthW, oneSixthH, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = newImage.createGraphics();
                graphics.drawImage(logImage, 0, 0, oneSixthW, oneSixthH, null);
                graphics.dispose();
                return drawNewImage(matrixImage, newImage);
            } else {
                return drawNewImage(matrixImage, logImage);
            }
        }
        return matrixImage;
    }

    /**
     * 将log图片画入二维码中
     * @param matrixImage 数据源
     * @param logImage log
     * @return 结果
     */
    private static BufferedImage drawNewImage(BufferedImage matrixImage, BufferedImage logImage) {
        // 画出中间含有log的二维码图形对象,x 是log图像显示的位置，y是log图像
        int x = (matrixImage.getWidth() - logImage.getWidth()) / 2;
        int y = (matrixImage.getHeight() - logImage.getHeight()) / 2;
        // 使用二维码图形创建图形工具
        Graphics2D erCodeUtil = matrixImage.createGraphics();
        erCodeUtil.drawImage(logImage, x, y, null);
        erCodeUtil.dispose();
        logImage.flush();
        return matrixImage;
    }

    /**
     * 将矩阵图形化
     * @param bitMatrix 数据源
     * @return 结果
     */
    private static BufferedImage toBufferredImage(BitMatrix bitMatrix) {
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                image.setRGB(i, j, bitMatrix.get(i, j) ? 0XFF000000 : 0XFFFFFF);
            }
        }
        return image;
    }

    private static final String CHARSET = "utf-8";
    private static final String FORMAT = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 200;
    // LOGO宽度
    private static final int LOGO_WIDTH = 60;
    // LOGO高度
    private static final int LOGO_HEIGHT = 60;

    public static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (logoPath == null || "".equals(logoPath)) {
            return image;
        }
        // 插入图片
        QRCodeUtil.insertImage(image, logoPath, needCompress);
        return image;
    }

    /**
     * 插入LOGO
     *
     * @param source 二维码图片
     * @param logoPath LOGO图片地址
     * @param needCompress 是否压缩
     * @throws Exception 异常
     */
    private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
        File file = new File(logoPath);
        if (!file.exists()) {
            throw new Exception("logo file not found.");
        }
        Image src = ImageIO.read(new File(logoPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > LOGO_WIDTH) {
                width = LOGO_WIDTH;
            }
            if (height > LOGO_HEIGHT) {
                height = LOGO_HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成二维码(内嵌LOGO)
     * 二维码文件名随机，文件名可能会有重复
     *
     * @param content 内容
     * @param logoPath LOGO地址
     * @param destPath 存放目录
     * @param needCompress 是否压缩LOGO
     * @throws Exception 异常
     */
    public static String encode(String content, String logoPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);
        mkdirs(destPath);
        String fileName = new Random().nextInt(99999999) + "." + FORMAT.toLowerCase();
        ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
        return fileName;
    }

    /**
     * 生成二维码(内嵌LOGO)
     * 调用者指定二维码文件名
     *
     * @param content 内容
     * @param logoPath LOGO地址
     * @param destPath 存放目录
     * @param fileName 二维码文件名
     * @param needCompress 是否压缩LOGO
     * @throws Exception 异常
     */
    public static String encode(String content, String logoPath, String destPath, String fileName, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);
        mkdirs(destPath);
        fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length())
                + "." + FORMAT.toLowerCase();
        ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
        return fileName;
    }

    /**
     * 当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．
     * (mkdir如果父目录不存在则会抛出异常)
     * @param destPath 存放目录
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content 内容
     * @param logoPath LOGO地址
     * @param destPath 存储地址
     * @throws Exception 异常
     */
    public static String encode(String content, String logoPath, String destPath) throws Exception {
        return QRCodeUtil.encode(content, logoPath, destPath, false);
    }

    /**
     * 生成二维码
     *
     * @param content 内容
     * @param destPath 存储地址
     * @param needCompress 是否压缩LOGO
     * @throws Exception 异常
     */
    public static String encode(String content, String destPath, boolean needCompress) throws Exception {
        return QRCodeUtil.encode(content, null, destPath, needCompress);
    }

    /**
     * 生成二维码
     *
     * @param content 内容
     * @param destPath 存储地址
     * @throws Exception 异常
     */
    public static String encode(String content, String destPath) throws Exception {
        return QRCodeUtil.encode(content, null, destPath, false);
    }

    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content 内容
     * @param logoPath LOGO地址
     * @param output 输出流
     * @param needCompress 是否压缩LOGO
     * @throws Exception 异常
     */
    public static void encode(String content, String logoPath, OutputStream output, boolean needCompress)
            throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);
        ImageIO.write(image, FORMAT, output);
    }

    /**
     * 生成二维码
     *
     * @param content 内容
     * @param output 输出流
     * @throws Exception 异常
     */
    public static void encode(String content, OutputStream output) throws Exception {
        QRCodeUtil.encode(content, null, output, false);
    }

    /**
     * 解析二维码
     *
     * @param file 二维码图片
     * @return 结果
     * @throws Exception 异常
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 解析二维码
     * @param path 二维码图片地址
     * @return 结果
     * @throws Exception 异常
     */
    public static String decode(String path) throws Exception {
        return QRCodeUtil.decode(new File(path));
    }

}
